<template>
  <viewer ref="viewers" :images="fileUrlList">
    <el-upload
      ref="upload"
      :auto-upload="true"
      :data="fileUploadInfoDto"
      :action="actionUrl"
      :file-list="fileList"
      :before-upload="beforeAvatarUpload"
      :on-preview="download"
      :on-success="uploadSuccess"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="limit"
      :on-exceed="handleExceed"
      :disabled="disabled"
      class="avatar-uploader"
      name="dmsFile"
      multiple
      list-type="picture-card"
    >
      <i class="el-icon-plus"/>
      <el-dialog :visible.sync="dialogVisible" title="图片" append-to-body>
        <img :src="image" width="100%" alt="" @dblclick="imagedownload">

      </el-dialog>
    </el-upload>
  </viewer>
</template>
<script>
import request from '@/utils/request'
import SERVER from '@/api/server'
import { deleteById } from '@/api/basedata/file.js'
export default {
  name: 'UploadFileimage',
  props: {
    limit: [String, Number],
    billType: [String],
    billId: {
      type: String,
      default: ''
    },
    fileType: {
      type: String,
      default: ''
    },
    fileDesc: {
      type: String,
      default: ''
    },
    maxSize: [String],
    disabled: {
      type: Boolean,
      default: false
    }

  },
  data() {
    return {
      fileUploadInfoDto: {
        billType: this.$props.billType,
        billId: this.$props.billId
      },
      actionUrl: `${SERVER.DMSCLOUD_BASEDATA}/file/save/2`,
      urlparams: {},
      count: 0,
      fileslength: 0,
      fileList: [],
      fileUrlList: [],
      fileIdStr: '',
      fileUploadIdStr: '',
      dialogVisible: false,
      image: ''
    }
  },
  computed: {
  },
  watch: {
    billId: function(newval, oldval) {
      //
      this.queryFiles()
    }
  },
  mounted() {
    this.queryFiles()
  },

  methods: {
    beforeAvatarUpload(file) {
      if (this.fileType != null && this.fileType !== '' && this.fileType !== undefined && this.fileDesc != null && this.fileDesc !== '' && this.fileDesc !== undefined && this.fileType.indexOf(file.name.substring(file.name.lastIndexOf('.'), file.name.length)) < 0) {
        this.$message({
          type: 'error',
          message: this.fileDesc
        })
        return false
      }
      if (this.maxSize != null && this.maxSize !== '' && this.maxSize !== undefined && file.size / 1024 / 1024 > parseInt(this.maxSize)) {
        this.$message({
          type: 'error',
          message: '上传文件大小需小于' + this.maxSize + 'MB!'
        })
        return false
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传 ${this.limit} 个文件!`)
    },
    handleChange(files, fileList) {
      console.log('=====change')
    },
    beforeRemove(file, fileList) {
      var id = file.key
      if (id == null || id === '') {
        id = file.response.fileUploadId
      }

      return new Promise((resolve, reject) => {
        this.$confirm('确定要删除\'' + file.name + '\'吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.deleteById(id, fileList)
          resolve(true)
        }).catch(() => {
          reject(new Error('获取数据失败'))
        })
      })
    },
    async deleteById(id, fileList) {
      deleteById(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功！'
        })
        this.fileUploadIdStr = this.fileUploadIdStr.replace(',;' + id, '')
        const params = '##@' + this.fileUploadIdStr.slice(2)
        // 添加属性
        this.$set(this.urlparams, this.billType, params)
        this.$emit('getparams', this.urlparams, fileList.length)
      })
    },
    handleRemove(files, fileList) {
    },

    uploadSuccess(res, file, fileList) {
      this.fileUrlList.push(file.url)
      this.fileUploadIdStr += ',;' + res.fileUploadId
      const params = '##@' + this.fileUploadIdStr.slice(2)
      // 添加属性
      this.$set(this.urlparams, this.billType, params)
      this.$emit('getparams', this.urlparams, fileList.length)
    },
    // 打开弹框
    queryFiles() {
      // 编辑 查询文件列表
      if (this.billId !== undefined && this.billId !== '') {
        const queryurl = `${SERVER.DMSCLOUD_BASEDATA}/file/billFiles/${
          this.billType
        }/${this.billId}`
        const params = {
          fileType: Number(this.billType),
          billId: Number(this.billId)
        }
        request
          .get(queryurl, params)
          .then(response => {
            /* this.fileList = response.initialPreviewConfig;
            let urls = response.initialPreview*/

            const fileList = response.initialPreviewConfig
            const urls = response.initialPreview
            // this.filelist = fileList
            if (fileList !== undefined && fileList.length > 0) {
              for (let i = 0; i < fileList.length; i++) {
                const obj = {}
                obj.name = fileList[i].caption
                obj.key = fileList[i].key
                obj.billType = urls[i].split('/')[3]
                obj.url = `${SERVER.DMSCLOUD_BASEDATA}` + urls[i]
                this.fileList.push(obj)
                this.fileUrlList.push(obj.url)
              }
            }
            this.$emit('getparams', this.urlparams, fileList.length)
          })
          .catch(({ err }) => {})
      }
    },
    // 文件上传
    imagedownload() {
      this.$refs.viewers.$viewer.show()
      // window.open(this.image, '_blank')
    },
    // 附件下载
    download(file) {
      /*    if (!!window.ActiveXObject || 'ActiveXObject' in window) {
        alert('推荐谷歌进行文件预览')
      } else {
        window.open(file.url) // blob格式地址
      }*/
      this.$refs.viewers.$viewer.show()
      /* this.dialogVisible = true
      this.image = file.url*/
    }
  }
}
</script>

